package com.yixun.qfbao.filters;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

public class JSONPFilter implements Filter {
	private static Logger log = Logger.getLogger(JSONPFilter.class);
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		response.setContentType("text/html; charset=UTF-8");
		HttpServletRequest req = (HttpServletRequest)request;
		HttpServletResponse res = (HttpServletResponse)response;
		log.info(req.getRequestURI());
		res.setContentType("text/html; charset=UTF-8");
		res.setHeader("Access-Control-Allow-Origin", "*");
		String callback = req.getParameter("callback");
		if(callback!=null&&!"".equals(callback.trim())){
			res.getOutputStream().print(callback+"(");
		}
		chain.doFilter(req, res);
		if(callback!=null&&!"".equals(callback.trim())){
			res.getOutputStream().print(");");
		}
	}

	@Override
	public void destroy() {
		
	}

}
